<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'material:need:pmMaterialneed:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #clSelect>
        <!--  -->
        <ListSelect
          selectType="materialSelect"
          :checkbox="true"
          :params="queryParams"
          :selectList="listSelectRef"
          @select="handSelect"
        />
      </template>
      <template #pmMaterialneedsList>
        <a-button
          class="mt-2 mr-2 mb-2"
          @click="openModal(true, {})"
          v-auth="'material:need:pmMaterialneed:edit'"
        >
          <Icon icon="simple-line-icons:calendar" /> {{ t('批量修改预计到达日期') }}
        </a-button>
        <BasicTable
          @register="registerPmMaterialneedsTable"
          @row-click="handlePmMaterialneedsRowClick"
        />
        <!-- <a-button
          class="mt-2"
          @click="handlePmMaterialneedsAdd"
          v-auth="'material:need:pmMaterialneed:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
    <Modal @register="register" @modifyjfdate="modifyjfdate" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialNeedPmMaterialneedForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmMaterialneed,
    pmMaterialneedNotcie,
    pmMaterialneedForm,
  } from '/@/api/material/need/pmMaterialneed';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { ListSelect } from '/@/components/ListSelect';
  import { useModal } from '/@/components/Modal';
  import Modal from './Modal.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.need.pmMaterialneed');
  const { showMessage } = useMessage();
  const record = ref<PmMaterialneed>({} as PmMaterialneed);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: '记录送货通知完成时间',
  }));

  const loadingRef = ref(false);
  let listSelectRef = ref([]);
  let queryParams = ref({});

  const inputFormSchemas: FormSchema[] = [
    // {
    //   label: t('工程名称'),
    //   field: 'projectno',
    //   fieldLabel: 'name',
    //   component: 'TreeSelect',
    //   componentProps: {
    //     api: pmProjectinformationTreeData,
    //     params: {
    //       isShowCode: true,
    //     },
    //     canSelectParent: false,
    //     allowClear: false,
    //     onChange: async (e) => {
    //       queryParams.value = {
    //         pcode: e,
    //       };
    //       let arr = await pmMaterialneedsTable.getDataSource();
    //       let arrNew = [...arr];
    //       arrNew.forEach(async (item, index) => {
    //         console.log(index);
    //         // console.log(item,'111');
    //         await pmMaterialneedsTable.deleteTableDataRecord(item);
    //         // console.log(item,'2222');
    //       });
    //     },
    //   },
    //   itemProps: { validateTrigger: 'blur' },
    //   required: true,
    // },
    // {
    //   label: t('工程编码'),
    //   field: 'projectno',
    //   component: 'Input',
    //   dynamicDisabled: true,
    //   componentProps: {
    //     maxlength: 50,
    //     // readonly: true,
    //   },
    //   required: true,
    // },
    // {
    //   label: t('材料清单'),
    //   field: 'clqd',
    //   component: 'Input',
    //   colProps: { lg: 24, md: 24 },
    //   slot: 'clSelect',
    //   show: false,
    // },
    {
      label: t('通知送货'),
      field: 'notedate',
      component: 'DatePicker',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        format: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm:ss' },
      },
      required: true,
    },
    {
      label: t('备注'),
      field: 'noteremark',
      component: 'InputTextArea',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        maxlength: 500,
      },
    },
    {
      label: t('需求明细'),
      field: 'pmMaterialneedsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmMaterialneedsList',
    },
  ];

  const [register, { openModal }] = useModal();

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerPmMaterialneedsTable, pmMaterialneedsTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handlePmMaterialneedsDelete.bind(this, record),
    //       },
    //       auth: 'material:need:pmMaterialneed:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmMaterialneedsTableData(_res: Recordable) {
    pmMaterialneedsTable.setColumns([
      {
        title: t('物料/水表编号'),
        dataIndex: 'metercode',
        dataLabel: 'basInv.mcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('物料/水表名称'),
        dataIndex: 'basInv.mname',
        width: 130,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.mstd',
        width: 130,
        align: 'left',
      },
      {
        title: t('需求数量'),
        dataIndex: 'querycount',
        width: 100,
        align: 'left',
      },
      {
        title: t('供应商'),
        dataIndex: 'supplier',
        width: 130,
        align: 'left',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 50,
        // },
        editRule: true,
      },
      {
        title: t('预计到达时间'),
        dataIndex: 'estimatedtime',
        width: 215,
        align: 'center',
        editable: true,
        edit: true,
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          // showTime: { format: 'HH:mm:ss' },
        },
        editRule: true,
      },
    ]);
    pmMaterialneedsTable.setTableData(record.value.pmMaterialneedsList || []);
  }

  function handlePmMaterialneedsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmMaterialneedsAdd() {
    if (!getFieldsValue().projectno) {
      showMessage('请先选择工程名称！');
      return;
    }
    listSelectRef.value = [];
    document.getElementById('form_item_clqd')?.click();
    // pmMaterialneedsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  async function handSelect(selectData) {
    let arr = await pmMaterialneedsTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.metercode == item.mcode) {
          flag = false;
        }
      });

      if (flag) {
        pmMaterialneedsTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          metercode: item.mcode,
          metername: item.mname,
          querycount: item.num,
        });
      }
    });
  }

  async function modifyjfdate(data) {
    for (const record of pmMaterialneedsTable.getDataSource()) {
      record.estimatedtime = data.estimatedtime;
      // console.log(data,'record');
    }
  }

  function handlePmMaterialneedsDelete(record: Recordable) {
    pmMaterialneedsTable.deleteTableDataRecord(record);
  }

  async function getPmMaterialneedsList() {
    let pmMaterialneedsListValid = true;
    let pmMaterialneedsList: Recordable[] = [];
    for (const record of pmMaterialneedsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmMaterialneedsListValid = false;
      }
      pmMaterialneedsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmMaterialneedsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmMaterialneedsList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmMaterialneedsListValid) {
      throw { errorFields: [{ name: ['pmMaterialneedsList'] }] };
    }
    return pmMaterialneedsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmMaterialneedForm(data);
    record.value = (res.pmMaterialneed || {}) as PmMaterialneed;
    record.value.__t = new Date().getTime();

    queryParams.value = {
      pcode: record.value.projectno,
    };
    setFieldsValue(record.value);
    setPmMaterialneedsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      // data.bpm = record.value.bpm; // 流程信息
      // data.status = record.value.status; // 提交状态
      // loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.pmMaterialneedsList = await getPmMaterialneedsList();
      // console.log('submit', params, data, record);
      const res = await pmMaterialneedNotcie(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      // loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
</style>
